/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbCloud			*/
/*	Author:		gong_libin			*/
/*	Date:		2012_01_20			*/
/*	File:		MrPipe.cpp			*/
/********************************************************/

#include "MrPipe.h"

CMrPipe::CMrPipe()
{
	m_pstPipe = NULL;
	m_pszResult = NULL;
}

CMrPipe::~CMrPipe()
{
	m_pstPipe = NULL;
	m_pszResult = NULL;
}

void CMrPipe::MrPipeClose()
{
	if (NULL != m_pstPipe) {
		pclose(m_pstPipe);
	}

	return;
}

char* CMrPipe::MrPipeResultGet()
{
	return m_pszResult;
}

void CMrPipe::MrPipeResultFree()
{
	if (NULL != m_pszResult) {
		free(m_pszResult);
		m_pszResult = NULL;
	}

	return;
}

void CMrPipe::MrPipeResultReset(ULONG ulSize)
{
	ULONG ulLength = 0;

	if (NULL != m_pszResult) {
		ulLength = ulSize ? ulSize : MR_PIPE;
		memset(m_pszResult, '\0', sizeof(char) * ulLength);
	}

	return;
}

int CMrPipe::MrPipeResultMalloc(ULONG ulSize)
{
	ULONG ulLength = 0;

	ulLength = ulSize ? ulSize : MR_PIPE;
	if (NULL != (m_pszResult = (char*)malloc(sizeof(char) * ulLength))) {
		memset(m_pszResult, '\0', sizeof(char) * ulLength);
	}
	else {
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrPipe::MrPipeOpen(char* pszCmd, char* pszType)
{
	m_pstPipe = popen(pszCmd, pszType);

	if (NULL == m_pstPipe) {
		MR_ERROR("%s\n", strerror(errno));
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

ULONG CMrPipe::MrPipeRead(ULONG ulSize)
{
	ULONG ulCount = 0;
	char szPacket[MR_PACKET] = { 0 };

	if (NULL != m_pszResult) {
		while (NULL != fgets(szPacket, MR_PACKET, m_pstPipe)) {
			ulCount += strlen(szPacket);
			if (ulCount < ulSize) {
				strcat(m_pszResult, szPacket);
				memset(szPacket, '\0', MR_PACKET);
			}
		}
	}

	return ulCount;
}
